# 补上下棋的测试例
# 同一机器跑测试

from time import time
import unittest
import socket

CONNECTION_REQUEST = bytes([0])
CONNECTION_RESPOND = bytes([1])

OBJECTIVE_ADDRESS = ("192.168.157.235", 4399)

class test_c_gobang(unittest.TestCase):
    
    def setUp(self) -> None:
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock_bind = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        self.sock_bind.bind(('', 4399))


    def tearDown(self) -> None:
        self.sock.close()
        self.sock_bind.close()


    def test_passiveConnect(self):
        # Given
        self.sock.sendto(CONNECTION_REQUEST, OBJECTIVE_ADDRESS)
        
        # Then
        data = self.sock.recv(1)
        # print(address)

        # Expect
        self.assertEqual(data, CONNECTION_RESPOND)


    def test_positiveConnect(self):    
        # When
        # 在另一端手动操作连接到此端
        data = self.sock_bind.recv(1)

        # Expect
        self.assertEqual(data, CONNECTION_REQUEST)
    

    def test_periodicallySendConnectRequest(self):
        # Given
        # 在另一端手动操作连接到此端
        recv_times = 3

        # Then
        prev = 0
        curr = 0

        data = self.sock_bind.recv(1)
        if data == CONNECTION_REQUEST:
            prev = time()

        for _ in range(recv_times):
            data = self.sock_bind.recv(1)
            if data == CONNECTION_REQUEST:
                curr = time()

                # Expect
                self.assertAlmostEqual(curr - prev, 3.0, delta = 0.5)
                
                prev = curr


    def test_punishment(self):
        # Given
        self.sock_bind.sendto(CONNECTION_RESPOND, OBJECTIVE_ADDRESS)

        # Then
        start = time()
        data = self.sock_bind.recv(1)
        end = time()

        # Expect
        self.assertAlmostEqual(end - start, 3 * 60, delta = 0.5)

unittest.main()